package com.carey.blog.action.impl;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.carey.blog.framework.latke.action.AbstractAction;
import com.carey.blog.framework.latke.action.ActionException;
import com.carey.blog.framework.latke.service.LangPropsService;
import com.carey.blog.framework.latke.util.Locales;
import com.carey.blog.listener.CareyBlogServletListener;
import com.carey.blog.model.Preference;
import com.carey.blog.util.Preferences;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * Abstract admin action.
 * 
 */
public abstract class AbstractAdminAction extends AbstractAction {

	/**
	 * Default serial version uid.
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger
			.getLogger(AbstractAdminAction.class.getName());
	/**
	 * Language service.
	 */
	private LangPropsService langPropsService = LangPropsService.getInstance();
	/**
	 * FreeMarker configuration.
	 */
	private Configuration configuration;
	/**
	 * Preference utilities.
	 */
	private Preferences preferenceUtils = Preferences.getInstance();

	@Override
	public void init() throws ServletException {
		configuration = new Configuration();
		configuration.setDefaultEncoding("UTF-8");
		
		try {
			final String webRootPath = CareyBlogServletListener.getWebRoot();

			configuration.setDirectoryForTemplateLoading(new File(webRootPath));
		} catch (final IOException e) {
			LOGGER.log(Level.SEVERE, e.getMessage(), e);
		}
	}

	@Override
	protected Map<?, ?> doFreeMarkerAction(
			final freemarker.template.Template template,
			final HttpServletRequest request, final HttpServletResponse response)
			throws ActionException {
		final Map<String, Object> ret = new HashMap<String, Object>();

		try {
			final JSONObject preference = preferenceUtils.getPreference();
			if (null == preference) {
				response.sendError(HttpServletResponse.SC_NOT_FOUND);
				return ret;
			}

			final String localeString = preference
					.getString(Preference.LOCALE_STRING);
			ret.put(Preference.LOCALE_STRING, localeString);
			final Locale locale = new Locale(Locales.getLanguage(localeString),
					Locales.getCountry(localeString));

			final Map<String, String> langs = langPropsService.getAll(locale);
			ret.putAll(langs);

			// For admin-preference.ftl only
			final StringBuilder timeZoneIdOptions = new StringBuilder();
			final String[] availableIDs = TimeZone.getAvailableIDs();
			for (int i = 0; i < availableIDs.length; i++) {
				final String id = availableIDs[i];
				String option = null;
				if (id.equals(preference.getString(Preference.TIME_ZONE_ID))) {
					option = "<option value=\"" + id + "\" selected=\"true\">"
							+ id + "</option>";
				} else {
					option = "<option value=\"" + id + "\">" + id + "</option>";
				}
				timeZoneIdOptions.append(option);
			}
			ret.put("timeZoneIdOptions", timeZoneIdOptions.toString());
		} catch (final Exception e) {
			LOGGER.log(Level.SEVERE, e.getMessage(), e);
			throw new ActionException("Language model fill error");
		}

		return ret;
	}

	@Override
	protected JSONObject doAjaxAction(final JSONObject data,
			final HttpServletRequest request, final HttpServletResponse response)
			throws ActionException {
		throw new UnsupportedOperationException();
	}

	@Override
	protected Template beforeDoFreeMarkerAction(
			final HttpServletRequest request, final HttpServletResponse response)
			throws ActionException {
		final String pageName = getPageName(request.getRequestURI());

		try {
			return configuration.getTemplate(pageName);
		} catch (final IOException e) {
			LOGGER.log(Level.SEVERE, e.getMessage(), e);
			throw new ActionException(e);
		}
	}
}
